﻿#encoding=UTF-8
from db_model import Gift, GiftTransaction,Product,Category
from taggable import Taggable,Tag
import datetime

class Admin:
  """Initializes the list of gifts in the datastore."""

  def initGifts(self):
    """Deletes any existing gifts and add the default gifts."""
    for gift in Gift.all():
      gift.delete()
    GIFT_NAMES = ['a cashew nut',
                  'a peanut',
                  'a hazelnut',
                  'a red pistachio nut']
    for name in GIFT_NAMES:
      gift = Gift()
      gift.name = name
      gift.put()

  def initGiftTransactions(self):
    """Deletes any existing gift transactions."""
    for t in GiftTransaction.all():
      t.delete()
  def getGiftNames(self):
    names = []
    for gift in Gift.all():
      names.append(gift.name)
    return names

  def getGiftTransactions(self):
    giftTransactions = []
    for t in GiftTransaction.all():
      giftTransactions.append("sender: %s, reciever: %s, gift: %s" %
          (t.sender_id, t.receiver_id, t.gift.key()))
    return giftTransactions

#import google.appengine.ext.webapp
from google.appengine.ext import webapp
from google.appengine.api import users

class AdminServer(webapp.RequestHandler):
    """Handles requests to /admin URLs and delegates to the Admin class."""

    def get(self):
        """Ensure that the user is an admin."""
        if not users.GetCurrentUser():
            loginUrl = users.CreateLoginURL(self.request.uri)
            self.response.out.write('<a href="%s">Login</a>' % loginUrl)
            return

        if not users.IsCurrentUserAdmin():
            self.response.out.write('You must be an admin to view this page.')
            return

        self._handleRequest()
    def _handleRequest(self):
      """Invokes methods from the Admin class based on the 'action' parameter"""
      admin = Admin()
      action = self.request.get('action')
      if action == 'init':
        admin.initGifts()
        admin.initGiftTransactions()
        msg = "Gifts have been initialized, gift transactions have been cleared."
        self.response.out.write(msg)
      elif action == 'list':
        self.response.out.write("Gifts = %s" % admin.getGiftNames())
        self.response.out.write("<br>")
        self.response.out.write("Gift Transactions = %s" % admin.getGiftTransactions())
      elif action == 'addproduct':
        if self.request.get('name') == '':
            self.response.out.write("""
            <script type="text/javascript">
function showpic()
{
	var url_value=document.getElementById("pic_url").value;
	//alert(url_value);
	var p = document.getElementById('spic');
	p.src=url_value;
	//document.pic1.src=url_value;
}
function showbigpic()
{
	var url_value=document.getElementById("big_pic_url").value;
	//alert(url_value);
	var p = document.getElementById('bpic');
	p.src=url_value;
	//document.pic1.src=url_value;
}
</script>
        <table cellpadding=0 cellspacing=0 style="margin-left:15px">
        <tr valign=top>
        <td style="height:62px;padding-left:92px" nowrap>
        <form name=f action=admin action=post><br/>
        <input type=hidden name=action id=action value=addproduct>
        类别：<input type=text name=category id=category size=42 maxlength=100> <br/>
        名称：<input type=text name=name id=name size=42 maxlength=100><br/>
        型号：<input type=text name=mod_num id=mod_num size=42 maxlength=100><br/>
        <img id='spic' src="/static/1.jpg"><br/>
        小图：<input type=text name=pic_url id=pic_url size=42 maxlength=100 onblur="showpic()"><br/>
        <img id='bpic' src="/static/1.jpg"><br>
        大图：<input type=text name=big_pic_url id=big_pic_url size=42 maxlength=100 onblur="showbigpic()"><br/>
        直接购买：<input type=text name=direct_buy_url id=direct_buy_url size=42 maxlength=100><br/>
        价格：<input type=text name=price id=price size=42 maxlength=100><br/>
        积分：<input type=text name=point id=point size=42 maxlength=100><br/>
        有货：<input type=checkbox name=is_online id=is_online ><br/>
        tags:<input type=text name=tags id=tags ><br/>
        <input type=submit value=提交 id=sb><span id=hp><br></span></form></td></tr></table>

        
        
        
        
            """);
        else:
            product = Product.get_or_create(self.request.get('direct_buy_url'))
            #if product is None:
            #    product = Product(key_name=self.request.get('direct_buy_url'))
            product.category = self.request.get('category')
            Category.get_or_create(product.category)
            product.name = self.request.get('name')
            product.mod_num = self.request.get('mod_num')
            product.pic_url = self.request.get('pic_url')
            product.big_pic_url = self.request.get('big_pic_url')
            product.direct_buy_url = self.request.get('direct_buy_url')
            product.price = float(self.request.get('price'))
            product.point = float(self.request.get('point'))
            product.is_online = (self.request.get('is_online') == 'on')
            product.tags = self.request.get('tags').encode('UTF-8')+","+self.request.get('category').encode('UTF-8')
            product.modded = datetime.datetime.now()
            #
            product.put()
            Category.set_product_count(product.category,Tag.get_by_name(product.category.encode('UTF-8')).tagged_count);
            self.response.out.write("""
            input ok<br>
            <a href="/admin?action=addproduct">click here to add more product</a>
            """)
            pass        

      else:
        html = []
        html.append('<a href="/admin?action=init">Initialize datastore</a><br>')
        html.append('<a href="/admin?action=list">List all data in datastore</a><br/>')
        html.append('<a href="/admin?action=addproduct">Add products into datastore</a><br/>')
       
        self.response.out.write(''.join(html))



